import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image,
	PixelRatio, ListView, ScrollView, Keyboard, Modal
} from 'react-native';
import { GLOBAL } from '../config/global';
import { style } from '../theme/style';

const scale = GLOBAL.SCALE;
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
let sideDataSource = [];
let mainDataSource = [];
let mainDataSelected = {};
const optionPicSourse = require('../imgs/global/option.png');
const selectedPicSourse = require('../imgs/global/success.png');

export default class ModalDoubleComponent extends Component {

	/* 
	属性： 
	modalVisible： 显示隐藏   true,false
	dataSource： 数据源   
	title： 标题
	selectVals： 选中的数据  一般用于数据回显
	single：单选,多选 控制
	cancelCheck：取消单选 默认false
	方法：
	cancelPress()   取消按钮回调
	confirmPress()  确定按钮回调
	*/



	constructor(props) {
		super(props);
		sideDataSource = [];  // 一级数据
		mainDataSource = [];  // 二级数据
		mainDataSelected = {};    // 选中 回显数据

		let { modalVisible, dataSource, title, selectVals, single } = props;
		if (selectVals && selectVals.length) {
			selectVals.forEach((item) => {
				mainDataSelected[item] = {};
			});
		}
		if (dataSource && dataSource.length) {
			dataSource.forEach((item) => {
				const { dataSource } = item;
				dataSource && dataSource.forEach((item) => {
					const { val } = item;
					if (mainDataSelected[val]) {
						console.log(item);
						mainDataSelected[val] = item;
					}
				});
			});
		}

		let curSideVal = null;
		if (dataSource[0]) {
			const { val } = dataSource[0];
			curSideVal = val;
			if (dataSource[0].dataSource) {
				mainDataSource = dataSource[0].dataSource;
			}
		}

		sideDataSource = dataSource;

		if (!modalVisible) {
			modalVisible = false;
		}

		this.title = '请选择';
		if (title) {
			this.title = title;
		}

		this.state = {
			sideDataSource: ds.cloneWithRows(dataSource.map((item, i) => {
				let current = false;
				if (!i) {
					current = true;
				}
				item.current = current;
				return item
			})),
			curSideVal,
		}

		this.renderSide = this.renderSide.bind(this);
		this.renderMain = this.renderMain.bind(this);
		this._pressSideRow = this._pressSideRow.bind(this);
		this._pressMainRow = this._pressMainRow.bind(this);
		this._setMainSelected = this._setMainSelected.bind(this);

	}

	componentWillMount () {
		this._setMainSelected();
	}

	componentWillReceiveProps (props) {
		let { modalVisible } = props;
		if (modalVisible) {
			Keyboard.dismiss();
		}
	}

	render () {
		return (
			<Modal animationType={"fade"}
				transparent={true}
				onRequestClose={() => { console.log(1) }}
				visible={this.props.modalVisible}  >
				<View style={styles.containerModal}>
					<View style={styles.listCell}>

						<View style={styles.listHead}>
							<TouchableOpacity onPress={
								() => {
									if (this.props.cancelPress) {
										this.props.cancelPress();
									}
								}} activeOpacity={0.5}>
								<Text style={styles.listHeadText}>取消</Text>
							</TouchableOpacity>
							<Text style={[styles.listHeadText, { fontSize: 18 * scale, color: '#404040' }]}>{this.title}</Text>
							<TouchableOpacity onPress={() => {
								const dataSelectedArray = [];
								for (let k in mainDataSelected) {
									dataSelectedArray.push(mainDataSelected[k]);
								}
								if (this.props.confirmPress) {
									this.props.confirmPress(dataSelectedArray);
								}
							}} activeOpacity={0.5}><Text style={styles.listHeadText}>确定</Text>
							</TouchableOpacity>
						</View>

						<View style={styles.listView}>
							<View style={styles.listSideWrap}>
								<ListView
									style={styles.listSideView}
									dataSource={this.state.sideDataSource}
									renderRow={this.renderSide}
									enableEmptySections={true}
								/>
							</View>
							<ScrollView
								horizontal={true}
								style={styles.listMainWrap}
							>
								{
									mainDataSource && mainDataSource.length > 0 ?
										(<ListView
											style={styles.listMainView}
											dataSource={this.state.mainDataSource}
											renderRow={this.renderMain}
											enableEmptySections={true}
										/>) :
										(<Text style={styles.emptyText}>暂无商品</Text>)
								}
							</ScrollView>
						</View>
					</View>
				</View>
			</Modal>
		);
	}

	//二级数据
	renderMain (main) {
		const { text, val, selected } = main;
		const picSource = selected ? selectedPicSourse : optionPicSourse;
		return (
			<TouchableOpacity onPress={() => {
				this._pressMainRow(main);
			}} activeOpacity={0.5} style={styles.listMainRow}>
				<Text style={[styles.listSideText, { width: 170 * scale, }]} numberOfLines={1}>{text}</Text>
				<Image source={picSource} style={styles.optionPic} />
			</TouchableOpacity>
		);
	}

	//一级数据
	renderSide (side) {
		const { text, val, dataSource, current } = side;
		const curStyle = (current) ? styles.listSideRowCur : null;
		return (
			<TouchableOpacity onPress={() => {
				if (this.state.curSideVal != val) {
					this._pressSideRow(val, dataSource || []);
				}
			}} activeOpacity={0.5} style={[styles.listSideRow, curStyle]}>
				<Text style={styles.listSideText}>{text}</Text>
			</TouchableOpacity>
		);
	}

	//一级勾选
	_pressSideRow (val, dataSource) {
		this.setState({
			curSideVal: val,
			mainDataSource: ds.cloneWithRows(dataSource),
			sideDataSource: ds.cloneWithRows(sideDataSource.map((item, i) => {
				let current = false;
				if (item.val == val) {
					current = true;
				}
				item.current = current;
				return item
			})),
		});
		mainDataSource = dataSource;
		this._setMainSelected();
	}

	//二级勾选
	_pressMainRow (main) {
		const { text, val } = main;

		if (this.props.single) {
			if (this.props.cancelCheck && mainDataSelected[val]) {
				mainDataSelected = {};
			} else {
				mainDataSelected = {};
				mainDataSelected[val] = main;
			}

		} else {
			if (mainDataSelected[val]) {
				delete mainDataSelected[val];
			} else {
				mainDataSelected[val] = main;
			}
		}
		this._setMainSelected();
	}

	//数据更新驱动
	_setMainSelected () {

		const mainDataSelect = mainDataSource.map((item, i) => {
			const { text, val } = item;
			let selected = false;
			if (mainDataSelected[val]) {
				selected = true;
			}
			item.selected = selected;
			return item;
		});
		this.setState({
			mainDataSource: ds.cloneWithRows(mainDataSelect)
		});
	}

}


const styles = StyleSheet.create({
	containerModal: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		backgroundColor: 'rgba(0, 0, 0, .3)',
		justifyContent: 'flex-end'
	},
	listHead: {
		flexDirection: 'row',
		justifyContent: 'space-around',
		height: 52 * scale,
		width: 375 * scale,
		alignItems: 'center',
	},
	listHeadText: {
		fontSize: 16 * scale,
		color: style.color.themeColor,
	},
	listCell: {
		backgroundColor: '#fff',
		width: 375 * scale,
		height: '70%',
	},
	listView: {
		flex: 1,
		flexDirection: 'row',
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
	},
	listSideWrap: {
		paddingBottom: 20 * scale,
		backgroundColor: '#F8F8F8'
	},
	listSideView: {
		width: 120 * scale,
		backgroundColor: '#F8F8F8',
	},
	listSideRow: {
		height: 50 * scale,
		justifyContent: 'center',
		alignItems: 'center',
	},
	listSideRowCur: {
		backgroundColor: '#fff',
	},
	listSideText: {
		fontSize: 13 * scale,
		color: '#8B8B8B',
	},
	listMainWrap: {
		paddingBottom: 20 * scale,
		backgroundColor: '#fff'
	},
	listMainView: {
		width: 255 * scale,
		paddingLeft: 40 * scale,
		paddingRight: 22 * scale,
		backgroundColor: '#fff',
	},
	listMainRow: {
		height: 50 * scale,
		alignItems: 'center',
		flexDirection: 'row',
		justifyContent: 'space-between',
	},
	optionPic: {
		width: 14 * scale,
		height: 14 * scale,
	},
	emptyText: {
		marginTop: 120 * scale,
		width: 255 * scale,
		color: '#8B8B8B',
		textAlign: 'center'
	}
})